package com.eascs.admin.o2o.internal.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.entity.PubDditem;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.service.PubDditemService;
import com.eascs.admin.o2o.internal.util.MoneyUtil;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.common.doc.pdf.PdfBuilder;
import com.eascs.common.doc.word.WordBuilder;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.nsEditDetail.entity.CustomerAssetInfo;
import com.eascs.crm.nsEditDetail.entity.O2oMainShopInfoEntity;
import com.eascs.crm.nsEditDetail.service.CustomerAssetInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.crm.nsEditDetail.service.IMainShopInfoService;
import com.eascs.gaczcontract.entity.CustomerBasicInfo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;

/**
 * @ClassName: ContractRestController
 * @Description: 合同打印
 * @author 张庆奇
 * @date 2016年6月12日 下午1:48:48
 * @version V1.0
 */
@RestController
public class ContractRestController extends BaseRestController {

	@Autowired
	private O2oLoanapplyService loanService;
	@Autowired
	private O2oLoanUserService loanUserService;
	@Autowired
	LoanapplyExpandService loanapplyExpandService;
	@Autowired
	PubDditemService pubDditemService;
	@Autowired
	O2oPubDdItemService ddItemService;
	@Reference
	SysOrgService sysOrgService;
	@Autowired
	CustomerAssetInfoService assetInfoService;
	@Reference
	IMainShopInfoService mainShopInfoService;
	@Autowired
	CustomerShopInfoService shopInfoService;
	
	@RequestMapping(value = "/checkBankInfo")
	public BaseRestResult<String> checkBankInfo(String loanapplyNo) {
		O2oLoanapplyEntity loan = loanService.findById(loanapplyNo);
		if (StringUtils.isEmpty(loan.getBankAccount()) || StringUtils.isEmpty(loan.getReceiveBank())) {
			return BaseRestResult.warn("请先保存银行卡信息");
		}
//		return BaseRestResult.info("正在下载中...").andRedirect("/makeContractPdf?loanapplyNo=" + loanapplyNo);
		return BaseRestResult.info("正在下载中...").andRedirect("/makeContractXmlToWord?loanapplyNo=" + loanapplyNo);
	}
	
	
	/**
	 * @Description:
	 *               <p>
	 *               村镇银行合同带数据下载改成Word版【XML转Word】
	 *               </p>
	 * @author LMX
	 * @date 2017年11月28日 上午9:54:40
	 */
	@RequestMapping(value = "/makeContractXmlToWord", method = RequestMethod.GET)
	public void makeContractXmlToWord(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if (loanapply == null) {
			return;
		}
		O2oLoanUserEntity loanUserEntity = loanService.findLoanUserEntity(loanapplyNo, loanapply.getLoanId());
		// 最后需要生产的模板文件
		String classPathFiles = "/wordTemplate/gacz_contract.xml";
		Map<String, Object> data = fillDataXML(loanapplyNo);
		OutputStream os = null;
		try {
			String outfile = "";
			outfile = loanUserEntity.getUserFullName() + "-村镇银行带数据合同.doc";
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				outfile = URLEncoder.encode(outfile, "UTF-8");
			} else {
				outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
			}
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/doc");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			WordBuilder.buildDocFromXml(os, data, classPathFiles);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}

	/**
	 * @Title: downloadContractPdf
	 * @Description: 生产pdf，并且下载pdf
	 * @author 张庆奇
	 * @param httpServletResponse
	 * @return void
	 * @throws @date
	 *             2016年6月12日 下午1:59:49
	 */
	@RequestMapping(value = "/makeContractPdf", method = RequestMethod.GET)
	public void downloadContractPdf(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if (loanapply == null) {
			return;
		}

		O2oLoanUserEntity loanUserEntity = loanUserService.findById(loanapply.getLoanId(), loanapplyNo);
		if (loanUserEntity == null) {
			return;
		}

		String bankName = loanapply.getBankLoanName();
		if (StringUtil.isNotBlank(bankName)) {
			bankName = bankName.toLowerCase();
		} else {
			return;
		}
		// 合同打印文件目录需要命名为该放款银行编码的小写
		String templateUrl = "/pdfTemplate/" + bankName;// 合同文件模板相对路径
		URL base = ContractRestController.class.getResource(templateUrl);
		String fileUrl = base.getFile();// 合同文件模板绝对路径
		File file = new File(fileUrl);
		File f[] = file.listFiles();// 列出目录下全部的文件
		List<String> tempClassPathFiles = new ArrayList<String>();// 生产的模板集合
		if (f != null) {// 判断此目录能否列出

			for (int i = 0; i < f.length; i++) {
				String tempPath = templateUrl + File.separator + f[i].getName();
				// 求每个模板需要打印的分数，命名方式一定要村镇农村银行的相同，比如gacz_contract0_1.pdf:前面的0是合同打印的顺序，后面的1是分数
				String fileNum = f[i].getName().substring(f[i].getName().lastIndexOf("_") + 1,
						f[i].getName().length() - 4);
				for (int j = 0; j < Integer.valueOf(fileNum); j++) {
					tempClassPathFiles.add(tempPath);// 根据需要的分数把不同的模板文件加入最后模板文件集合
				}

			}

		}
		// 最后需要生产的模板文件
		String[] classPathFiles = tempClassPathFiles.toArray(new String[tempClassPathFiles.size()]);

		Map<String, Object> data = fillData(loanapplyNo);

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		try {
			PdfBuilder.mergePdfFilesAndBuild(classPathFiles, data, outputStream);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		OutputStream os = null;
		try {
			String outfile = "";
			outfile = loanUserEntity.getUserFullName() + "-借款合同.pdf";
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				outfile = URLEncoder.encode(outfile, "UTF-8");
			} else {
				outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
			}
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/pdf");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			os.write(outputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}

	}

	/**
	 * @Description:
	 *               <p>
	 *               填充XML数据
	 *               </p>
	 * @author LMX
	 * @date 2017年11月28日 下午1:50:48
	 */
	private Map<String, Object> fillDataXML(String loanapplyNo) {
		Map<String, Object> data = new HashMap<>();
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		NumberFormat nf = new DecimalFormat(",###.00");
		O2oLoanUserEntity loanUserEntity = loanUserService.findById(loanapply.getLoanId(), loanapplyNo);
		LoanapplyExpand applyExpand = loanapplyExpandService.queryLoanapplyNo(loanapplyNo);
		CustomerBasicInfo customer = loanService.getCustomerEntityById(loanUserEntity.getId());
		CustomerAssetInfo asset = assetInfoService.queryById(loanapplyNo);
		O2oMainShopInfoEntity shop = mainShopInfoService.getByLoanNo(loanapplyNo);
//		CustomerShopInfoEntity shop = new CustomerShopInfoEntity();
//		List<CustomerShopInfoEntity> infoList = shopInfoService.list(loanapplyNo);//门店
//		if (!infoList.isEmpty()) {
//			if (infoList.size() > 1) {
//				for (CustomerShopInfoEntity shopInfo : infoList) {
//					if (shopInfo.getShoptype().equals("MAN")) {// 客户主门店里面的营业面积
//						shop = shopInfo;
//					}
//				}
//			} else {
//				shop = infoList.get(0);
//			}
//		}
		
		if (loanapply != null) {
			ActOrgEntity actOrgEntity = sysOrgService.getOrgByUnitNo(loanapply.getLtd());
			
			if (loanapply.getOperationModel().equals("PTDB")) {
				data.put("aName", actOrgEntity.getOrgFullName());// 甲方
				data.put("aAddress",  actOrgEntity.getOfficeAddress());// 甲方地址
			} else {
				data.put("aName", "深圳市怡亚通流通服务有限公司");// 甲方
				data.put("aAddress",  "深圳市前海深港合作区前湾一路1号A栋201室");// 甲方地址
			}
			
			data.put("ltd_mobile", actOrgEntity.getSponsorTel());// 经营单位电话
			data.put("ltd_office_address", actOrgEntity.getOfficeAddress());// 经营单位办公地址
			data.put("ltd_name", actOrgEntity.getOrgFullName());// 经营名称
			
			data.put("receiveBank", loanapply.getReceiveBank());// 借款银行名称
			data.put("open_account_bank_full_name", loanapply.getReceiveBank());// 借款银行名称
			data.put("guarantee_way_xinyong", "信用");// 担保方式
			data.put("bankActno", loanapply.getBankActno());// 贷款账号
			data.put("billCode", "国安-借-" + loanapply.getBillCode());// 贷款编号
			data.put("billCode1", "村镇银行-合-" + loanapply.getBillCode());// 协议编号
			if (!"".equals(loanapply.getEaMount()) && loanapply.getEaMount() != null) {
				String bankAmountBigWrite = MoneyUtil
						.toChinese(formatComma2BigDecimal(loanapply.getEaMount(),2).toString());
				System.out.println(bankAmountBigWrite);
				
				data.put("bankAmountBigWrite", bankAmountBigWrite);// 银行批复金额大写
				data.put("bankTAmountBigWrite", bankAmountBigWrite.substring(0, bankAmountBigWrite.length() - 2));// 银行复批金额大写去‘元整’
				
				data.put("bankAmount", "￥" + formatComma2BigDecimal(loanapply.getEaMount(),2));// 申请金额万元
				data.put("bankAmount", nf.format(formatComma2BigDecimal(loanapply.getEaMount(),2)));// 银行批复金额小写
				
				String[] mountItem = buildMountNumber(loanapply.getEaMount());
				for (int i = 0; i < mountItem.length; i++) {
					data.put("mountItem" + i, mountItem[i]);
				}
			}
			
			if (loanapply.getLoanrate() != null) {
				BigDecimal loanrate = loanapply.getLoanrate().multiply(new BigDecimal(100));
				data.put("loanrate", formatComma2BigDecimal(loanrate,2).toString());// 借款利率
			}
			data.put("loanTerm", loanapply.getLoanTerm()+"");// 借款期限
			if (loanapply.getRepayMentway() != null) {
				if (loanapply.getRepayMentway().equals("AKT")) {
					data.put("repayMentway", "等额本金");// 还款方式
					data.put("repayMentwayNo", "(2)");
				} else if (loanapply.getRepayMentway().equals("RMT")) {
					data.put("repayMentway", "按月付息，到期还本");// 还款方式
					data.put("repayMentwayNo", "(1)");
				} else {
					data.put("repayMentway", "等额本息");// 还款方式
					data.put("repayMentwayNo", "(2)");
				}
			}
			
			data.put("bank_account", loanapply.getBankAccount());// 银行卡号(放款和还款卡号)
			
			if (loanapply.getGuarAnteeWay() != null) {
				
				PubDditem p = pubDditemService.queryPubDditem("9941", loanapply.getGuarAnteeWay());
				if (p != null) {
					data.put("guar_antee_way", p.getItemName());// 担保方式
				}
			}
			
			if (loanapply.getManagefeerate() != null) {
				BigDecimal managefeerate = loanapply.getManagefeerate().multiply(new BigDecimal(100));
				data.put("managefeerate", formatComma2BigDecimal(managefeerate,2).toString());// 管理费率
			}
			if (loanapply.getDepositrate() != null) {
				BigDecimal depositrate = loanapply.getDepositrate().multiply(new BigDecimal(100));
				data.put("depositrate", formatComma2BigDecimal(depositrate,2).toString());// 保证金费率
			}
			
			if (loanapply.getRisk() != null) {
				BigDecimal saferate = loanapply.getRisk().multiply(new BigDecimal(100));
				data.put("saferate", formatComma2BigDecimal(saferate,4).toString());// 风险补偿金费率
			}
			
			data.put("paymentType", "资金周转");// 借款用途
			
			
			
		}
		
		data.put("lonerName", loanUserEntity.getUserFullName());// 借款人
		data.put("age", IdNOToAge(loanUserEntity.getDocumentNo())+"");// 借款人年龄
		String sex = "";
		if ("F".equals(loanUserEntity.getSex())) {
			sex = "女";
		} else if ("M".equals(loanUserEntity.getSex())) {
			sex = "男";
		}
		data.put("sex", sex);// 借款人性别
		data.put("idNumber", loanUserEntity.getDocumentNo());// 身份证号码
		data.put("mobile", loanUserEntity.getUserPhone());// 手机号
		
		if (customer != null) {
			
			String recipientAddress=getRecipientAdress(customer);
			data.put("recipientAddress",recipientAddress );// 收件地址
			
			String countAdress=getCountAdress(customer);
			data.put("countAdress", countAdress);// 户籍地址
			
			if (customer.getAccountProvince() != null) {
				PubDditem p = pubDditemService.queryPubDditem("159", customer.getAccountProvince());
				if (p != null) {
					data.put("accountProvince", p.getItemName());// 户口所在省
				}
			}
			
			if (customer.getAccountCity() != null) {
				PubDditem p = pubDditemService.queryPubDditem("160", customer.getAccountCity());
				if (p != null) {
					data.put("accountCity", p.getItemName());// 户口所在市区
				}
			}
			if (customer.getEducation() != null) {
				PubDditem p = pubDditemService.queryPubDditem("107", customer.getEducation());
				if (p != null) {
					data.put("education", p.getItemName());// 学历
				}
			}
			
		}else{
			data.put("recipientAddress", "");// 收件地址
			data.put("countAdress", "");// 户籍地址
			data.put("accountProvince", "");// 户口所在省
			data.put("accountCity", "");// 户口所在市区
			data.put("education", "");// 学历
		}
		
		if (asset != null) {
			data.put("ownEstateNum", asset.getOwnEstateNum()+"");// 自有房产数量
			data.put("mortgageNum", asset.getMortgageNum()+"");// 按揭房产数量
			data.put("notmortgageNum", (asset.getOwnEstateNum() - asset.getMortgageNum())+"");// 按揭房产数量
			data.put("ownVehiclesNum", asset.getOwnVehiclesNum()+"");// 自有车辆数
			data.put("unsecuredNum", asset.getUnsecuredNum()+"");// 无抵押车辆数
			data.put("vehicleMortgageNum", asset.getVehicleMortgageNum()+"");// 辆数按揭数量
			
		}
		if (shop != null) {
			
			if (!"".equals(shop.getStupdate()) && shop.getStupdate() != null) {
				String year = DateUtils.formateStandDateTime(shop.getStupdate()).substring(0, 4);
				String mouth = DateUtils.formateStandDateTime(shop.getStupdate()).substring(5, 7);
				data.put("year", year);// 门店成立年
				data.put("mouth", mouth);// 门店成立月
			}else {
				data.put("year", "");// 门店成立年
				data.put("mouth", "");// 门店成立月
			}
			String Businesshours="";
			if (shop.getBusinesshours()!=null) {
				Businesshours= new SimpleDateFormat("yyyy-MM-dd").format(shop.getBusinesshours());
			}
			String mainShopAdd="";
			if (!StringUtils.isEmpty(shop.getShopprovince())) {
				String province=ddItemService.findPubdditemNameByCodeisall("province", shop.getShopprovince());
				if (!StringUtils.isEmpty(province)) {
					mainShopAdd+=province;
				}
			}
			if (!StringUtils.isEmpty(shop.getShopcity())) {
				String city=ddItemService.findPubdditemNameByCodeisall("city", shop.getShopcity());
				if (!StringUtils.isEmpty(city)) {
					mainShopAdd+=city;
				}
			}
			if (!StringUtils.isEmpty(shop.getShopcounty())) {
				String country=ddItemService.findPubdditemNameByCodeisall("country", shop.getShopcounty());
				if (!StringUtils.isEmpty(country)) {
					mainShopAdd+=country;
				}
			}
			mainShopAdd+=shop.getShopaddress();
			String organizationForm="";
			if (!StringUtils.isEmpty(shop.getOrganizationForm())) {
				organizationForm=ddItemService.findPubdditemO2ONameByCodeall("organizationForm", shop.getOrganizationForm());
			}
			String officeaddress="";
			if (!StringUtils.isEmpty(shop.getOfficeprovince())) {
				String province=ddItemService.findPubdditemNameByCodeisall("province", shop.getOfficeprovince());
				if (!StringUtils.isEmpty(province)) {
					officeaddress+=province;
				}
			}
			if (!StringUtils.isEmpty(shop.getOfficecity())) {
				String city=ddItemService.findPubdditemNameByCodeisall("city", shop.getOfficecity());
				if (!StringUtils.isEmpty(city)) {
					officeaddress+=city;
				}
			}
			if (!StringUtils.isEmpty(shop.getOfficecounty())) {
				String country=ddItemService.findPubdditemNameByCodeisall("country", shop.getOfficecounty());
				if (!StringUtils.isEmpty(country)) {
					officeaddress+=country;
				}
			}
			officeaddress+=shop.getOfficeaddress();
			data.put("controllername", loanUserEntity.getUserFullName());// 借款人
			data.put("controllerIdnum", loanUserEntity.getDocumentNo());// 身份证号码
			data.put("controllerMobile", loanUserEntity.getUserPhone());// 手机号
			data.put("mainShopAdd", mainShopAdd);// 门店地址
			data.put("businesshours", Businesshours);// 营业时间
			data.put("officeaddress", officeaddress);// 已方单位地址
			data.put("licenceName", shop.getLicenceName());// 营业执照名称
			data.put("blrNumber", shop.getBlrNumber());// 营业执照注册号
			data.put("organizationForm", organizationForm);//组织形式
//			data.put("shopTelephone", shop.getTelephone());//门店电话
//			data.put("businessarea", String.valueOf(shop.getBusinessarea()));// 客户主门店里面的营业面积
//			data.put("mainproducts", shop.getMainproducts());// 主要经营产品
			data.put("shopTelephone", "");//门店电话
			data.put("businessarea", "");// 客户主门店里面的营业面积
			data.put("mainproducts", "");// 主要经营产品
		}else {
			data.put("controllername", "");// 借款人
			data.put("controllerIdnum", "");// 身份证号码
			data.put("controllerMobile", "");// 手机号
			data.put("mainShopAdd", "");// 门店地址
			data.put("businesshours", "");// 营业时间
			data.put("officeaddress", "");// 已方单位地址
			data.put("licenceName", "");// 营业执照名称
			data.put("blrNumber", "");// 营业执照注册号
			data.put("organizationForm", "");//组织形式
			data.put("officeaddress", "");// 已方单位地址
			data.put("year", "");// 门店成立年
			data.put("mouth", "");// 门店成立月
			data.put("shopTelephone", "");//门店电话
			data.put("businessarea", "");// 客户主门店里面的营业面积
			data.put("mainproducts", "");// 主要经营产品
		}
		
		if (applyExpand != null) {
			if (applyExpand.getRecManger() != null) {
				System.out.println("管理费:" + formatComma2BigDecimal(applyExpand.getRecManger(),2));
				data.put("rec_manger", "￥" + formatComma2BigDecimal(applyExpand.getRecManger(),2));// 管理费
			}
			if (applyExpand.getRecDeposite() != null) {
				data.put("rec_deposite", "￥" + formatComma2BigDecimal(applyExpand.getRecDeposite(),2));// 保证费
			}
			if (applyExpand.getRecRisk() != null) {
				data.put("rec_risk", "￥" + formatComma2BigDecimal(applyExpand.getRecRisk(),2));// 保证费
			}
			BigDecimal total = new BigDecimal("0");
			BigDecimal recManger = new BigDecimal("0");
			BigDecimal recDeposite = new BigDecimal("0");
			BigDecimal recRisk = new BigDecimal("0");
			recManger = applyExpand.getRecManger() == null ? recManger : applyExpand.getRecManger();
			recDeposite = applyExpand.getRecDeposite() == null ? recDeposite : applyExpand.getRecDeposite();
			recRisk = applyExpand.getRecRisk() == null ? recRisk : applyExpand.getRecRisk();
			total = recManger.add(recDeposite).add(recRisk);
			data.put("rec_total_samll", formatComma2BigDecimal(total,2).toString());// 保证费
			data.put("rec_total_big", MoneyUtil.toChinese(formatComma2BigDecimal(total,2).toString()));// 保证费
			
		}
		//担保人
		O2oLoanUserEntity guarantorByGuara = loanUserService.queryDBById(loanapplyNo);
		if (guarantorByGuara != null) {
			data.put("guarByGuara", guarantorByGuara.getUserFullName());// 担保人
			data.put("guarIdCardByGuara", guarantorByGuara.getDocumentNo());// 担保人身份证
			data.put("guarMobileByGuara", guarantorByGuara.getUserPhone());// 担保人电话号码
		}else{
			data.put("guarByGuara", "");// 担保人
			data.put("guarIdCardByGuara", "");// 担保人身份证
			data.put("guarMobileByGuara", "");// 担保人电话号码
		}
		
		O2oLoanUserEntity loanSpouseUserEntity = loanUserService.findSpouseId(loanUserEntity.getLoanId(), loanapplyNo);
		if (loanSpouseUserEntity != null) {
			data.put("mateName", loanSpouseUserEntity.getUserFullName());// 配偶
			data.put("mateIdCard", loanSpouseUserEntity.getDocumentNo());// 配偶身份证
			data.put("mateMobile", loanSpouseUserEntity.getUserPhone());// 配偶手机号
			
			CustomerBasicInfo mateBasicInfo = loanService.getCustomerEntityById(loanSpouseUserEntity.getId());
			
			if (mateBasicInfo != null) {
				String recipientAdress = getCountAdress(mateBasicInfo);
				data.put("mateRecipientAdress", recipientAdress);// 配偶收件地址
				data.put("work_unit", mateBasicInfo.getWorkUnit());// 配偶工作单位
			} 
		} else {
			data.put("mateName", "");// 配偶
			data.put("mateIdCard", "");// 配偶身份证
			data.put("mateMobile", "");// 配偶手机号
			data.put("mateRecipientAdress", "");// 配偶收件地址
			data.put("work_unit", "");// 配偶工作单位
		}
		return data;
		
	}
	
	
	/**
	 * @Title: fillData
	 * @Description: 填充pdf数据
	 * @author 张庆奇
	 * @return
	 * @return Map<String,Object>
	 * @throws @date
	 *             2016年6月12日 下午2:00:06
	 */
	private Map<String, Object> fillData(String loanapplyNo) {
		Map<String, Object> data = new HashMap<>();
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		NumberFormat nf = new DecimalFormat(",###.00");
		O2oLoanUserEntity loanUserEntity = loanUserService.findById(loanapply.getLoanId(), loanapplyNo);
		LoanapplyExpand applyExpand = loanapplyExpandService.queryLoanapplyNo(loanapplyNo);
		CustomerBasicInfo customer = loanService.getCustomerEntityById(loanUserEntity.getId());
		CustomerAssetInfo asset = assetInfoService.queryById(loanapplyNo);
		O2oMainShopInfoEntity shop = mainShopInfoService.getByLoanNo(loanapplyNo);

		if (loanapply != null) {
			ActOrgEntity actOrgEntity = sysOrgService.getOrgByUnitNo(loanapply.getLtd());

			if (loanapply.getOperationModel().equals("PTDB")) {
				data.put("aName", actOrgEntity.getOrgFullName());// 甲方
				data.put("aAddress",  actOrgEntity.getOfficeAddress());// 甲方地址
			} else {
				data.put("aName", "深圳市怡亚通流通服务有限公司");// 甲方
				data.put("aAddress",  "深圳市前海深港合作区前湾一路1号A栋201室");// 甲方地址
			}

			data.put("ltd_mobile", actOrgEntity.getSponsorTel());// 经营单位电话
			data.put("ltd_office_address", actOrgEntity.getOfficeAddress());// 经营单位办公地址
			data.put("ltd_name", actOrgEntity.getOrgFullName());// 经营名称

			data.put("receiveBank", loanapply.getReceiveBank());// 借款银行名称
			data.put("open_account_bank_full_name", loanapply.getReceiveBank());// 借款银行名称
			data.put("guarantee_way_xinyong", "信用");// 担保方式
			data.put("bankActno", loanapply.getBankActno());// 贷款账号
			data.put("billCode", "国安-借-" + loanapply.getBillCode());// 贷款编号
			data.put("billCode1", "村镇银行-合-" + loanapply.getBillCode());// 协议编号
			if (!"".equals(loanapply.getEaMount()) && loanapply.getEaMount() != null) {
				String bankAmountBigWrite = MoneyUtil
						.toChinese(formatComma2BigDecimal(loanapply.getEaMount(),2).toString());
				System.out.println(bankAmountBigWrite);

				data.put("bankAmountBigWrite", bankAmountBigWrite);// 银行批复金额大写
				data.put("bankAmountBigWrite-2", bankAmountBigWrite.substring(0, bankAmountBigWrite.length() - 2));// 银行复批金额大写去‘元整’

				data.put("loanAmount", "￥" + formatComma2BigDecimal(loanapply.getEaMount(),2));// 申请金额万元
				data.put("bankAmount", nf.format(formatComma2BigDecimal(loanapply.getEaMount(),2)));// 银行批复金额小写

				String[] mountItem = buildMountNumber(loanapply.getEaMount());
				for (int i = 0; i < mountItem.length; i++) {
					data.put("mountItem" + i, mountItem[i]);
				}
			}

			if (loanapply.getLoanrate() != null) {
				BigDecimal loanrate = loanapply.getLoanrate().multiply(new BigDecimal(100));
				data.put("loanrate", formatComma2BigDecimal(loanrate,2));// 借款利率
			}
			data.put("loanTerm", loanapply.getLoanTerm());// 借款期限
			if (loanapply.getRepayMentway() != null) {
				if (loanapply.getRepayMentway().equals("AKT")) {
					data.put("repayMentway", "等额本金");// 还款方式
					data.put("repayMentwayNo", "(2)");
				} else if (loanapply.getRepayMentway().equals("RMT")) {
					data.put("repayMentway", "按月付息，到期还本");// 还款方式
					data.put("repayMentwayNo", "(1)");
				} else {
					data.put("repayMentway", "等额本息");// 还款方式
					data.put("repayMentwayNo", "(2)");
				}
			}

			data.put("bank_account", loanapply.getBankAccount());// 银行卡号(放款和还款卡号)

			if (loanapply.getGuarAnteeWay() != null) {

				PubDditem p = pubDditemService.queryPubDditem("9941", loanapply.getGuarAnteeWay());
				if (p != null) {
					data.put("guar_antee_way", p.getItemName());// 担保方式
				}
			}

			if (loanapply.getManagefeerate() != null) {
				BigDecimal managefeerate = loanapply.getManagefeerate().multiply(new BigDecimal(100));
				data.put("managefeerate", formatComma2BigDecimal(managefeerate,2));// 管理费率
			}
			if (loanapply.getDepositrate() != null) {
				BigDecimal depositrate = loanapply.getDepositrate().multiply(new BigDecimal(100));
				data.put("depositrate", formatComma2BigDecimal(depositrate,2));// 保证金费率
			}

			if (loanapply.getRisk() != null) {
				BigDecimal saferate = loanapply.getRisk().multiply(new BigDecimal(100));
				data.put("saferate", formatComma2BigDecimal(saferate,4));// 风险补偿金费率
			}
			
			data.put("paymentType", "资金周转");// 借款用途
				

			
		}

		data.put("lonerName", loanUserEntity.getUserFullName());// 借款人
		data.put("age", IdNOToAge(loanUserEntity.getDocumentNo()));// 借款人年龄
		String sex = "";
		if ("F".equals(loanUserEntity.getSex())) {
			sex = "女";
		} else if ("M".equals(loanUserEntity.getSex())) {
			sex = "男";
		}
		data.put("sex", sex);// 借款人性别
		data.put("idNumber", loanUserEntity.getDocumentNo());// 身份证号码
		data.put("mobile", loanUserEntity.getUserPhone());// 手机号

		if (customer != null) {

			String recipientAddress=getRecipientAdress(customer);
			data.put("recipientAddress",recipientAddress );// 收件地址
			
			String countAdress=getCountAdress(customer);
			data.put("countAdress", countAdress);// 户籍地址

			if (customer.getAccountProvince() != null) {
				PubDditem p = pubDditemService.queryPubDditem("159", customer.getAccountProvince());
				if (p != null) {
					data.put("accountProvince", p.getItemName());// 户口所在省
				}
			}

			if (customer.getAccountCity() != null) {
				PubDditem p = pubDditemService.queryPubDditem("160", customer.getAccountCity());
				if (p != null) {
					data.put("accountCity", p.getItemName());// 户口所在市区
				}
			}
			if (customer.getEducation() != null) {
				PubDditem p = pubDditemService.queryPubDditem("107", customer.getEducation());
				if (p != null) {
					data.put("education", p.getItemName());// 学历
				}
			}

		}

		if (asset != null) {
			data.put("ownEstateNum", asset.getOwnEstateNum());// 自有房产数量
			data.put("mortgageNum", asset.getMortgageNum());// 按揭房产数量
			data.put("notmortgageNum", asset.getOwnEstateNum() - asset.getMortgageNum());// 按揭房产数量
			data.put("ownVehiclesNum", asset.getOwnVehiclesNum());// 自有车辆数
			data.put("unsecuredNum", asset.getUnsecuredNum());// 无抵押车辆数
			data.put("vehicleMortgageNum", asset.getVehicleMortgageNum());// 辆数按揭数量

		}
		if (shop != null) {

			if (!"".equals(shop.getStupdate()) && shop.getStupdate() != null) {
				String year = DateUtils.formateStandDateTime(shop.getStupdate()).substring(0, 4);
				String mouth = DateUtils.formateStandDateTime(shop.getStupdate()).substring(5, 7);
				data.put("year", year);// 门店成立年
				data.put("mouth", mouth);// 门店成立月
			}
			String Businesshours="";
			if (shop.getBusinesshours()!=null) {
				Businesshours= new SimpleDateFormat("yyyy-MM-dd").format(shop.getBusinesshours());
			}
			String mainShopAdd="";
			if (!StringUtils.isEmpty(shop.getShopprovince())) {
				String province=ddItemService.findPubdditemNameByCodeisall("province", shop.getShopprovince());
				if (!StringUtils.isEmpty(province)) {
					mainShopAdd+=province;
				}
			}
			if (!StringUtils.isEmpty(shop.getShopcity())) {
				String city=ddItemService.findPubdditemNameByCodeisall("city", shop.getShopcity());
				if (!StringUtils.isEmpty(city)) {
					mainShopAdd+=city;
				}
			}
			if (!StringUtils.isEmpty(shop.getShopcounty())) {
				String country=ddItemService.findPubdditemNameByCodeisall("country", shop.getShopcounty());
				if (!StringUtils.isEmpty(country)) {
					mainShopAdd+=country;
				}
			}
			mainShopAdd+=shop.getShopaddress();
			String organizationForm="";
			if (!StringUtils.isEmpty(shop.getOrganizationForm())) {
				organizationForm=ddItemService.findPubdditemO2ONameByCodeall("organizationForm", shop.getOrganizationForm());
			}
			String officeaddress="";
			if (!StringUtils.isEmpty(shop.getOfficeprovince())) {
				String province=ddItemService.findPubdditemNameByCodeisall("province", shop.getOfficeprovince());
				if (!StringUtils.isEmpty(province)) {
					officeaddress+=province;
				}
			}
			if (!StringUtils.isEmpty(shop.getOfficecity())) {
				String city=ddItemService.findPubdditemNameByCodeisall("city", shop.getOfficecity());
				if (!StringUtils.isEmpty(city)) {
					officeaddress+=city;
				}
			}
			if (!StringUtils.isEmpty(shop.getOfficecounty())) {
				String country=ddItemService.findPubdditemNameByCodeisall("country", shop.getOfficecounty());
				if (!StringUtils.isEmpty(country)) {
					officeaddress+=country;
				}
			}
			officeaddress+=shop.getOfficeaddress();
			data.put("controllername", loanUserEntity.getUserFullName());// 借款人
			data.put("controllerIdnum", loanUserEntity.getDocumentNo());// 身份证号码
			data.put("controllerMobile", loanUserEntity.getUserPhone());// 手机号
			data.put("mainShopAdd", mainShopAdd);// 门店地址
			data.put("businesshours", Businesshours);// 营业时间
			data.put("officeaddress", officeaddress);// 已方单位地址
			data.put("licenceName", shop.getLicenceName());// 营业执照名称
			data.put("blrNumber", shop.getBlrNumber());// 营业执照注册号
			data.put("organizationForm", organizationForm);//组织形式
		}

		if (applyExpand != null) {
			if (applyExpand.getRecManger() != null) {
				System.out.println("管理费:" + formatComma2BigDecimal(applyExpand.getRecManger(),2));
				data.put("rec_manger", "￥" + formatComma2BigDecimal(applyExpand.getRecManger(),2));// 管理费
			}
			if (applyExpand.getRecDeposite() != null) {
				data.put("rec_deposite", "￥" + formatComma2BigDecimal(applyExpand.getRecDeposite(),2));// 保证费
			}
			if (applyExpand.getRecRisk() != null) {
				data.put("rec_risk", "￥" + formatComma2BigDecimal(applyExpand.getRecRisk(),2));// 保证费
			}
			BigDecimal total = new BigDecimal("0");
			BigDecimal recManger = new BigDecimal("0");
			BigDecimal recDeposite = new BigDecimal("0");
			BigDecimal recRisk = new BigDecimal("0");
			recManger = applyExpand.getRecManger() == null ? recManger : applyExpand.getRecManger();
			recDeposite = applyExpand.getRecDeposite() == null ? recDeposite : applyExpand.getRecDeposite();
			recRisk = applyExpand.getRecRisk() == null ? recRisk : applyExpand.getRecRisk();
			total = recManger.add(recDeposite).add(recRisk);
			data.put("rec_total_samll", formatComma2BigDecimal(total,2));// 保证费
			data.put("rec_total_big", MoneyUtil.toChinese(formatComma2BigDecimal(total,2).toString()));// 保证费

		}
		//担保人
		O2oLoanUserEntity guarantorByGuara = loanUserService.queryDBById(loanapplyNo);
		if (guarantorByGuara != null) {
			data.put("guarByGuara", guarantorByGuara.getUserFullName());// 担保人
			data.put("guarIdCardByGuara", guarantorByGuara.getDocumentNo());// 担保人身份证
			data.put("guarMobileByGuara", guarantorByGuara.getUserPhone());// 担保人电话号码
		}
		
		O2oLoanUserEntity loanSpouseUserEntity = loanUserService.findSpouseId(loanUserEntity.getLoanId(), loanapplyNo);
		if (loanSpouseUserEntity != null) {
			data.put("mateName", loanSpouseUserEntity.getUserFullName());// 配偶
			data.put("mateIdCard", loanSpouseUserEntity.getDocumentNo());// 配偶身份证
			data.put("mateMobile", loanSpouseUserEntity.getUserPhone());// 配偶手机号
			
			CustomerBasicInfo mateBasicInfo = loanService.getCustomerEntityById(loanSpouseUserEntity.getId());
	
			if (mateBasicInfo != null) {
				String recipientAdress = getCountAdress(mateBasicInfo);
				data.put("mateRecipientAdress", recipientAdress);// 收件地址
				data.put("work_unit", mateBasicInfo.getWorkUnit());// 配偶手机号
			}
		} 
		return data;

	}

	private boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	private boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	private boolean isNumber(String value) {
		return isInteger(value) || isDouble(value);
	}

	private BigDecimal formatComma2BigDecimal(Object obj,int num) {
		String val = String.valueOf(obj);
		if (val == null)
			return new BigDecimal("0.00");

		val = val.replaceAll(",", "");
		if (!isNumber(val))
			return new BigDecimal("0.00");

		BigDecimal decimal = new BigDecimal(val);
		decimal = decimal.setScale(num, BigDecimal.ROUND_UP);

		return decimal;

	}

	private static String[] buildMountNumber(Number number) {
		DecimalFormat df = new DecimalFormat("0.00");
		String mountStr = df.format(number);
		mountStr = "￥" + mountStr.replace(".", "");
		String[] numberArray = new String[10];
		int j = 0;
		for (int i = 0; i < numberArray.length; i++) {
			numberArray[i] = "";
			if (mountStr.length() >= 10 - i) {
				numberArray[i] = mountStr.substring(j, j + 1);
				j++;
			}
		}
		return numberArray;
	}

	// 根据身份证号输出年龄
	public static int IdNOToAge(String IdNO) {
		int leh = IdNO.length();
		String dates = "";
		if (leh == 18) {
			dates = IdNO.substring(6, 10);
			SimpleDateFormat df = new SimpleDateFormat("yyyy");
			String year = df.format(new Date());
			int u = Integer.parseInt(year) - Integer.parseInt(dates);
			return u;
		} else {
			dates = IdNO.substring(6, 8);
			return Integer.parseInt(dates);
		}

	}
	
	/**
	 * @Title: getCountAdress
	 * @Description: 获取户口地址
	 * @author 张庆奇
	 * @param basic
	 * @return
	 * @return String
	 * @throws
	 * @date 2017年10月9日 下午5:01:35
	 */
	private String getCountAdress(CustomerBasicInfo basic) {
		String acountAdress = "";
		if (StringUtil.isNotBlank(basic.getAccountProvince())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("9", basic.getAccountProvince());
			if (p != null) {
				acountAdress = acountAdress + p.getItemName();
			}
		}

		if (StringUtil.isNotBlank(basic.getAccountCity())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("10", basic.getAccountCity());
			if (p != null) {
				acountAdress = acountAdress + p.getItemName();
			}
		}

		if (StringUtil.isNotBlank(basic.getAccountAounty())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("11", basic.getAccountAounty());
			if (p != null) {
				acountAdress = acountAdress + p.getItemName();
			}
		}

		if (basic.getPermanentresidence() != null) {
			acountAdress = acountAdress + basic.getPermanentresidence();
		}
		return acountAdress;

	}
	
	
	/**
	 * @Title: getRecipientAdress
	 * @Description: 获取收件人地址
	 * @author 张庆奇
	 * @param basic
	 * @return
	 * @return String
	 * @throws
	 * @date 2017年10月9日 下午5:10:47
	 */
	private String getRecipientAdress(CustomerBasicInfo basic) {
		String recipientAdress = "";
		if (StringUtil.isNotBlank(basic.getRecipientProvince())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("9", basic.getRecipientProvince());
			if (p != null) {
				recipientAdress = recipientAdress + p.getItemName();
			}
		}

		if (StringUtil.isNotBlank(basic.getRecipientCity())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("10", basic.getRecipientCity());
			if (p != null) {
				recipientAdress = recipientAdress + p.getItemName();
			}
		}

		if (StringUtil.isNotBlank(basic.getRecipientCounty())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("11", basic.getRecipientCounty());
			if (p != null) {
				recipientAdress = recipientAdress + p.getItemName();
			}
		}

		if (basic.getRecipientAddress() != null) {
			recipientAdress = recipientAdress + basic.getRecipientAddress();
		}
		return recipientAdress;

	}
}
